var express = require('express')
var router = express.Router()

// router.use(jwtAuth)
const { getAll, getOne, exec } = require('../db/index')

// 获取所有用户
// GET /users?page=1&size=5
router.get('/', async (req, res) => {
  // 解析请求参数
  const { page = 1, size = 5 } = req.query
  let sql = `select count(*) as total from blog_user`
  let { total } = await getOne(sql) //{ total: 15 }
  // 偏移量 = (page-1)*size
  let offset = (page - 1) * size
  // 操作数据库
  sql = `select id,username,selected,email,personNote from blog_user limit ${offset},${size}`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '获取所有用户成功',
    result: {
      total,
      data,
    },
  })
})

// 关键字搜索
router.get('/search', async (req, res) => {
  const { page = 1, size = 5, keywords } = req.query
  let sql = `select count(*) as total from blog_user where username like '%${keywords}%'`
  let { total } = await getOne(sql)
  let offset = (page - 1) * size
  sql = `select id,username,selected,email,personNote from blog_user where username like '%${keywords}%' limit ${offset},${size} `
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: {
      total,
      data,
    },
  })
})

// 获取单个用户
router.get('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `select * from blog_user where id = ${id}`
  const data = await getOne(sql)
  res.send({
    code: 0,
    message: '获取单个用户成功',
    result: data,
  })
})

// 新增用户
router.post('/', async (req, res) => {
  const { username, password } = req.body
  let sql = `insert into blog_user (username,password) values ('${username}','${password}')`
  const { insertId } = await exec(sql)
  sql = `select id,username from blog_user where id = ${insertId}`
  const resData = await getOne(sql)
  res.send({
    code: 0,
    message: '新增用户成功',
    result: resData,
  })
})

// 修改用户选中状态
router.put('/select', async (req, res) => {
  const { id, selected } = req.body
  let sql = `update blog_user set selected = '${selected}' where id = ${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '修改状态成功',
    result: {
      id,
      selected,
    },
  })
})

// PUT/user/id {usernam:'new',password:'new'}
router.put('/:id', async (req, res) => {
  const { id } = req.params
  const { username, password } = req.body

  let sql = `update blog_user set username='${username}',password='${password}' where id = ${id}`
  await exec(sql)

  res.send({
    code: 0,
    message: '修改成功',
    result: {
      id,
      username,
      password,
    },
  })
})

// 删除选中
router.delete('/delselected', async (req, res) => {
  let sql = `delete from blog_user where selected = 1`
  await exec(sql)
  res.send({
    code: 0,
    message: '删除选中成功',
    result: '',
  })
})

router.delete('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `delete from blog_user where id =${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '删除成功',
    result: '',
  })
})

module.exports = router
